import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { BladeData } from "../../../../shared/blade/blade-data";
import { DicValueListComponent } from "../../../../module/basic/dic/dic-value-list/dic-value-list.component";
import { Farm } from "../../../../entity/farm.model";
import { FarmService } from "../../../../service/farm.service";
import { CompanyService } from "../../../../service/company.service";
import { Company } from "../../../../entity/company.model";
import { ApplicationService } from "../../../../service/application.service";
import { Setofvalue } from "../../../../entity/setofvalue.model";

@Component({
    selector: 'app-farm-edit',
    templateUrl: './farm-edit.component.html',
    styleUrls: ['./farm-edit.component.css']
})

export class FarmEditComponent extends BladeContainerBase<Farm>{

    /**
     * 风场集合
     * 
     * @type {Farm[]}
     * @memberof FarmEditComponent
     */
    farms: Farm[] = [];
    original: Farm[] = [];

    /**
     *  公司集合
     * 
     * @type {Company[]}
     * @memberof FarmEditComponent
     */
    companys:Company[] =[]

    setofvalues:Setofvalue[];

    constructor(
        private application: ApplicationService,
        private fb: FormBuilder,
        private farmService: FarmService,
        private companyService: CompanyService) {       
        super(fb);
        this.setofvalues =this.application.setKeyDict["FarmCategory"];
        // this.bladeData.headIcon=  this.application.currentMenu.menuIcon;
    }
    ngOnInit(): void {
        //编辑  
        if (!this.isNew) {
            this.commands = [
                new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
                new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
            ]
        }
        else {
            this.currentEntity = new Farm(0, 1, "", "", "风场", "", 0, "", 0, 0, "", "", "", "", "", "", "",true)
        }
        super.ngOnInit();
    }
    /**
    * 初始化数据
    *   获取风场集合、公司集合
    * 
    * @memberof BladeContainerBase
    */
   
    initData(): any | Observable<any> | Promise<any> {
        this.farmService.getFarms()
            .then(res => {         
                this.original = [...res];
                this.farms = [...this.original];
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);


        this.companyService.getComponys()
            .then(res => {
                this.companys = [...res];
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);

    }

    exeSaveChange(blade: any): void {
        this.saveChange();
    }
    canSaveChange(blade: any): boolean {
        return this.hasChange() && !this.hasError();
    }
    exeReset(blade: any): void {
        return this.formGroup.reset(this.currentEntity);
    }
    canReset(blade: any): boolean {
        return this.hasChange();
    }
    /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
    createForm() {

        this.formGroup = this.fromBuider.group({
            "companyId": [this.currentEntity.companyId, [
                Validators.required,
                Validators.pattern("[0-9]{1,20}"),
                Validators.maxLength(20),
            ]],
            "farmId": [this.currentEntity.farmId, [
                Validators.required,
                Validators.pattern("[0-9]{1,20}"),
                Validators.maxLength(20),
            ]],

            "farmCode": [this.currentEntity.farmCode, [
                Validators.required,
                Validators.pattern("[0-9a-zA-Z_.]{1,20}"),
                Validators.maxLength(20),
            ], (control: FormControl): any => this.farmCodeAsnyValidator(control)],
            "farmName": [this.currentEntity.farmName, [
                Validators.required,
                Validators.maxLength(20),
            ], (control: FormControl): any => this.farmNameAsnyValidator(control)],

            "unShowName": [this.currentEntity.unShowName, [
            ],],
            "farmCategory": [this.currentEntity.farmCategory, [
                Validators.required,
                Validators.maxLength(20),
            ]],
            "simpleCode": [this.currentEntity.simpleCode, [
                Validators.required,
                Validators.maxLength(20),
            ], (control: FormControl): any => this.simpleCodeAsnyValidator(control)],
            "capacity": [this.currentEntity.capacity, [

                Validators.maxLength(7)
            ]],
            "productionDate": [this.currentEntity.productionDate, [//????????????
                Validators.required
                //new Date().getFullYear()+"/"+(new Date().getMonth()+1)+"/"+new Date().getDate();
                //Validators.pattern("([0-9]{4})[-,/]([0-9]{2})[-,/]([0-9]{2})"),
                // Validators.maxLength(10),
            ]],
            "posx": [this.currentEntity.posx, [
                Validators.pattern("^[0-9]+([.]{1}[0-9]+){0,1}$"),
                Validators.maxLength(7),
            ]],
            "posy": [this.currentEntity.posy, [
                Validators.pattern("^[0-9]+([.]{1}[0-9]+){0,1}$"),
                Validators.maxLength(7),
            ]],
            "contact": [this.currentEntity.contact, [
                Validators.maxLength(10),
            ]],
            "telNo": [this.currentEntity.telNo, [
                Validators.pattern("^(1)([3,4,5,7,8])([0-9]{9})$"),
                Validators.maxLength(11),
            ]],
            "email": [this.currentEntity.email, [
                Validators.pattern("^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"),
                Validators.maxLength(20),
            ]],
            "faxNo": [this.currentEntity.faxNo, [

                Validators.pattern("^([0-9]{3,4}-)?[0-9]{7,8}$"),
                Validators.maxLength(20),
            ]],
            "city": [this.currentEntity.city, [
                Validators.maxLength(20),
            ]],
            "addr": [this.currentEntity.addr, [
                Validators.maxLength(50),
            ]],
            "introduce": [this.currentEntity.introduce, [
                Validators.maxLength(200),
            ]],
            "seq": [this.currentEntity.seq, [
        Validators.required,
        Validators.pattern("[0-9]{1,5}"),
        Validators.maxLength(5)
      ]],
           

        });
    }




    /**
    * 设置表单错误对象
    * 
    * 
    * @memberof BladeContainerBase
    */
    setFormError(): void {
        this.formErrors = {
            'companyId': '',
            'farmId': '',
            'farmCode': '',
            'unShowName': '',
            'farmName': '',
            'farmCategory': '',
            'simpleCode': '',
            'capacity': '',
            'productionDate': '',
            'posx': '',
            'posy': '',
            'contact': '',
            'telNo': '',
            'email': '',
            'faxNo': '',
            'city': '',
            'addr': '',
            'introduce': '',
            'seq': '',
        };
    }
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            // farmId
            'companyId': {
                'required': '公司ID不能为空。',
                'maxlength': '公司ID不能多于20个字符长度。',
                'pattern': '公司ID由数字。',
                'exist': '公司ID已存在',
            },
            'farmId': {
                'required': '风场ID不能为空。',
                'maxlength': '风场ID不能多于20个字符长度。',
                'pattern': '风场ID由数字。',
                'exist': '风场ID已存在',
            },
            'unShowName': {
                'required': '是否显示风场名称不能为空',
              },

            'farmCode': {
                'required': '风场代码不能为空。',
                'maxlength': '风场代码不能多于20个字符长度。',
                'pattern': '风场代码由数字、字母组成。',
                'exist': '风场代码已存在',
            },
            'farmName': {
                'required': '风场名称不能为空。',
                'maxlength': '风场名称不能多于20个字符长度。',
                'pattern': '风场名称由汉字组成。',
                'exist': '风场名称已存在',
            },
            'farmCategory': {
                'required': '风场类别不能为空。',
                'maxlength': '风场类别不能多于20个字符长度。',
                //'pattern': '风场类别由汉字组成。',
            },
            'simpleCode': {
                'required': '简单标示不能为空。',
                'maxlength': '简单标示不能多于20个字符长度。',
                'pattern': '简单标示由汉字组成。',
                'exist': '简单标示已存在',
            },
            'capacity': {
                'required': '总装机容量不能为空。',
                'maxlength': '总装机容量不能多于7个字符长度。',
                'pattern': '总装机容量小数或数字组成。',
            },
            'productionDate': {
                'required': '建场日期不能为空。',
                'maxlength': '建场日期不能多于20个字符长度。',
                'pattern': '建场日期格式不正确。',
            },
            'posx': {//?
                'required': '风场X轴坐标不能为空。',
                'maxlength': '风场X轴坐标不能多于7个字符长度。',
                'pattern': '风场X轴坐标由数字组成。',
            },
            'posy': {//?
                'required': '风场Y轴坐标不能为空。',
                'maxlength': '风场Y轴坐标不能多于7个字符长度。',
                'pattern': '风场Y轴坐标由数字组成。',
            },
            'contact': {
                'required': '联系人不能为空。',
                'maxlength': '联系人不能多于20个字符长度。',
                'pattern': '联系人由汉字组成。',
                'exist': '联系人已存在',
            },
            'telNo': {//?
                'required': '联系电话不能为空。',
                'maxlength': '联系电话不能多于11个字符长度。',
                'pattern': '电话号码不正确。',
                'exist': '电话已存在',
            },
            'email': {
                'required': '电子邮箱不能为空。',
                'maxlength': '电子邮箱不能多于20个字符长度。',
                'pattern': '电子邮箱由字母、数字、-、@符号组成。',
                'exist': '电子邮箱已存在',
            },
            'faxNo': {//?
                'required': '传真不能为空。',
                'maxlength': '传真不能多于20个字符长度。',
                'pattern': '传真由数字、-组成。',
                'exist': '传真已存在',
            },
            'city': {
                'required': '所在城市不能为空。',
                'maxlength': '所在城市不能多于20个字符长度。',
                'pattern': '所在城市由汉字组成。',
            },
            'addr': {
                'required': '风场地址不能为空。',
                'maxlength': '风场地址不能多于50个字符长度。',
                'pattern': '风场地址由汉字组成。',
                'exist': '风场地址已存在',
            },
            'introduce': {
                'required': '风场简介不能为空。',
                'maxlength': '风场简介不能多于200个字符长度。',
                'pattern': '风场简介由汉字组成。',
            },
            'seq': {
                'required': '排序值不能为空。',
                'pattern': '排序值必须在0-255之间的数字。',
                'maxlength': '排序值不能多于5个字符长度。',
            }
        };
    }


    /**
     * 异步校验farmName是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof FarmEditComponent
     */
    farmNameAsnyValidator(control: FormControl): any {
        
         if (!control.value || control.value == this.currentEntity.farmName) {
            return Observable.of(null);
        }
 
        return this.farmService.hasFarmName(control.value, this.currentEntity.farmId)
            .map(res => res ? { exist: true } : null);
    }


    /**
     * 异步校验farmCode是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof FarmEditComponent
     */
    farmCodeAsnyValidator(control: FormControl): any {
        if (!control.value || control.value == this.currentEntity.farmCode) {
            return Observable.of(null);
        }
        return this.farmService.hasFarmCode(control.value, this.currentEntity.farmId)
            .map(res => res ? { exist: true } : null);


    }
    /**
     * 异步校验 简单标识 是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof FarmEditComponent
     */
    simpleCodeAsnyValidator(control: FormControl): any {
        if (!control.value || control.value == this.currentEntity.simpleCode) {
            return Observable.of(null);
        }
        return this.farmService.hasSimpleCode(control.value, this.currentEntity.farmId)
            .map(res => res ? { exist: true } : null);

    }

    /**
     * 创建
     * 
     * 
     * @memberof DicKeyEditComponent
     */
    onCreate() {
        if (!this.hasError()) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.farmCode = formValue.farmCode;
            this.currentEntity.companyId = formValue.companyId;
            this.currentEntity.farmId = formValue.farmId;
            this.currentEntity.farmName = formValue.farmName;
            this.currentEntity.farmCategory = formValue.farmCategory;
            this.currentEntity.simpleCode = formValue.simpleCode;
            this.currentEntity.capacity = formValue.capacity;
            this.currentEntity.productionDate = formValue.productionDate;
            this.currentEntity.posx = formValue.posx;
            this.currentEntity.posy = formValue.posy;
            this.currentEntity.contact = formValue.contact;
            this.currentEntity.telNo = formValue.telNo;
            this.currentEntity.email = formValue.email;
            this.currentEntity.faxNo = formValue.faxNo;
            this.currentEntity.city = formValue.city;
            this.currentEntity.addr = formValue.addr;
            this.currentEntity.introduce = formValue.introduce;
            this.currentEntity.seq = formValue.seq;
            this.currentEntity.unShowName = formValue.unShowName;
            this.farmService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }

    saveChange(): any | Promise<any> | Observable<any> {
        if (this.canSaveChange(this.currentBlade)) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.companyId = formValue.companyId;
            this.currentEntity.farmId = formValue.farmId;
            this.currentEntity.farmCode = formValue.farmCode;
            this.currentEntity.farmName = formValue.farmName;
            this.currentEntity.farmCategory = formValue.farmCategory;
            this.currentEntity.simpleCode = formValue.simpleCode;
            this.currentEntity.capacity = formValue.capacity;
            this.currentEntity.productionDate = formValue.productionDate;
            this.currentEntity.posx = formValue.posx;
            this.currentEntity.posy = formValue.posy;
            this.currentEntity.contact = formValue.contact;
            this.currentEntity.telNo = formValue.telNo;
            this.currentEntity.email = formValue.email;
            this.currentEntity.faxNo = formValue.faxNo;
            this.currentEntity.city = formValue.city;
            this.currentEntity.addr = formValue.addr;
            this.currentEntity.seq = formValue.seq;
            this.currentEntity.introduce = formValue.introduce;
            this.currentEntity.unShowName = formValue.unShowName;
            return this.farmService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/farm/farm-edit/farm-edit.component.ts